import { login, getUserInfoAPI } from '@/api/user'
import { Message } from 'element-ui'
import router from '@/router'
export default {
  namespaced: true,
  state: {
    token: null,
    userInfo: {},
    dikedeTime: 0
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    romoveToken(state) {
      state.token = null
    },
    setUserInfo(state, useInfo) {
      state.userInfo = useInfo
    },
    romoveUserInfo(state) {
      state.userInfo = null
    },
    setDikedeTime(state, time) {
      state.dikedeTime = time
    }
  },
  actions: {
    async loginAction(context, data) { // 发送登录请求，获取token 在后续中还会用到的，所以很直接抽取 出来
      // 发送请求获取用户token
      const res = await login(data)
      console.log('登录', res)
      context.commit('setToken', res.data.token)
      context.commit('setDikedeTime', Date.now())
      if (res.data.success === true || res.data.success === undefined) {
        Message.success('登录成功')
        router.push('/')
      } else {
        Message.error(res.data.msg)
      }
      const res1 = await getUserInfoAPI(res.data.userId)
      console.log(res1)
      context.commit('setUserInfo', res1.data)
    },
    layoutAction(context) {
      context.commit('romoveToken')
      context.commit('romoveUserInfo')
    }
  }
}
